import { stringify } from 'qs';
import { omitBy, isUndefined } from 'lodash';

import { getMd5, getToken, request } from '@/utils';
import { fingerprintFetch } from '@/utils/request';

export const fetchData = async (params: { [x: string]: any }) => {
  if (params.cpuUsage) {
    params.minCpuUsage = params.cpuUsage[0];
    params.maxCpuUsage = params.cpuUsage[1];
    delete params.cpuUsage;
  }

  if (params.memoryUsage) {
    params.minMemoryUsage = params.memoryUsage[0];
    params.maxMemoryUsage = params.memoryUsage[1];
    delete params.memoryUsage;
  }

  if (params.rangeTime) {
    params.startTime = params.rangeTime[0].valueOf();
    params.endTime = params.rangeTime[1].valueOf();
    delete params.rangeTime;
  }

  const json = JSON.stringify(omitBy(params, isUndefined));

  const url = `${window.g.url}/msdrivingmonitor/tracking/page`;

  const result = await (
    await fingerprintFetch(url, {
      method: 'POST',
      body: json,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        OptAuthorization: `${getToken()}`,
        shaSign: getMd5(json),
      },
    })
  ).json();

  if (result.statusCode !== '0') return {};

  return result.data;
};

export const fetchBrand = async () => {
  const result = await request('/common/vehicle/getcurrentbrand');

  if (result.statusCode !== '0') return [];

  return result.data;
};

export const fetchSeries = async (brandId: string) => {
  const result = await request('/common/vehicle/getserieslist?brandId=' + brandId);

  if (result.statusCode !== '0') return [];

  return result.data;
};

export const fetchType = async (query: { brandId: string; seriesId: string }) => {
  const result = await request(`/common/vehicle/gettypelist?${stringify(query)}`);

  if (result.statusCode !== '0') return [];

  return result.data;
};

export const fetchModelStage = async ()=>{
  const result = await request('/msdrivingmonitor/tracking/modelStage?pageNo=0&pageSize=999');

  if (result.statusCode!== '0') return [];

  return result.data;
}

export const fetchModuleName = async ()=>{
  const result = await request('/msdrivingmonitor/module/name?pageNo=0&pageSize=999');

  if (result.statusCode!== '0') return [];

  return result.data;
}
